package com.somnus.androidkotlindemo.adapter

import android.content.Context
import android.support.v7.widget.RecyclerView
import android.support.v7.widget.RecyclerView.Adapter
import android.view.View
import android.view.ViewGroup
import com.somnus.androidkotlindemo.R
import com.somnus.androidkotlindemo.bean.UserBean
import kotlinx.android.synthetic.main.item_recycler.view.*


/**
 * Created by Somnus on 2017/6/13.
 * @Description:  原生的RecyclerView Adapter
 */
class RecyclerViewAdapter(val items: List<UserBean>, val context: Context) : Adapter<RecyclerViewAdapter.ViewHolder>() {

    override fun onBindViewHolder(holder: ViewHolder?, position: Int) {
        val kotlinBean = items[position]
        //改变作用域，with{}都是属于itemView .  holder.itemView
        with(holder?.itemView!!) {
            textView2.text = "姓名：" + kotlinBean.name
            textView3.text = "年龄：" + kotlinBean.age
            setOnClickListener { mListener?.invoke(position) }
        }

    }

    override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): ViewHolder {
//        val view = LayoutInflater.from(context).inflate(R.layout.item_recycler, null)
        val view = View.inflate(context, R.layout.item_recycler, null)
        return ViewHolder(view)

    }

    override fun getItemCount(): Int {
        return items.size
    }

    class ViewHolder(itemView: View?) : RecyclerView.ViewHolder(itemView)


    //一个函数变量mListener， 他的输入为int，返回值为Unit(kotlin的null，不过是个具体的对象)
    var mListener: ((pos: Int) -> Unit)? = null

    //set函数
    fun setOnClickItemListener(listener: (pos: Int) -> Unit) {
        mListener = listener
    }


}
